<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect,
  useMessage,
  NFlex,
  NAvatar,
  NSelect, NUpload,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import { getToken } from '@/utils'
import { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'

defineOptions({ name: '项目配置' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
import default_image from '@/assets/images/mz.jpg'

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '项目',
  initForm: {
    interval:30
  },
  doCreate: api.createSettingProject,
  doUpdate: api.updateSettingProject,
  doDelete: api.deleteSettingProject,
  refresh: () => $table.value?.handlerefresh(),
})
const data = reactive({
  token: getToken(),
  uploadAction: base_path+'api/appointment/project/file',
  deptOption: [],
  gotypeData: [
    {
      label: '无跳转',
      value: 0,
    },
    {
      label: '跳转文章',
      value: 1,
    },
  ],
  InstiumentData: [],
  ProjectData: [],
  upload: null,
  fileListLength: 0,
  goods:[]
})
onMounted(() => {
  api.getSettingProjectList().then((res) => (data.ProjectData = res.data))
  api.getallgoods().then((res) => (data.goods = res.data))
  api.getInstrumentList().then((res) => (data.InstiumentData.value = res.data))
  $table.value?.handleSearch()
})

//上传封面图
const message = useMessage();
const customRequestMethod = (options) => {
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        console.log(data, 'datatat');
        if (data.code === 200) {
          modalForm.value.cover = data.data.url
          message.success('封面图上传成功');
          options.onProgress(data);
        }else{
          message.error(data.msg);
        }
      })
}

const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  if (data.code === 200) {
    file.url = data.data.url
    message.success('上传成功')
  } else {
    message.error(data.data)
  }

  return file
}


function  level_format(level,data){
  let ret = ""
  if (data) {
    data.forEach((item) => {
    if(item.value === level){
      ret = item.label
    }
  })
  }
  
  return ret
}
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '名称',
    key: 'name',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
    fixed: 'left',
  },
  {
    title: '排序',
    key: 'sort',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '类别',
    key: 'type_name',
    align: 'center',
    width: 60,
    ellipsis: { tooltip: true },
    render(row) {  
      return h(
        NTag,
        { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
        { default: () => row.type_name }
      )
    },
  },
     {
    title: '仪器',
    key: 'pid',
    align: 'center',
    width: 60,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
        NTag,
        { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
        { default: () => level_format(row.pid,data.InstiumentData.value) }
      )
    },
  },
    {
    title: '时长',
    key: 'interval',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '封面图',
    key: 'cover',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
    render(row) {
      return h(NFlex, {},
          [h(NAvatar, {
            src: row.cover,
            width: 30,
            fallbackSrc: default_image,
          })]
      )

    },
  },
         {
    title: '商品',
    key: 'goods_info.name',
    align: 'center',
    width: 60,
    ellipsis: { tooltip: true },
  },
    {
    title: '价格',
    key: 'sku_info.sku_level[1]',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '状态',
    key: 'status',
    width: 50,
    align: 'center',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.status,
        loading: !!row.publishing,
        checkedValue: true,
        uncheckedValue: false,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handleEdit(row)
                if (!modalForm.value.files) {
                  modalForm.value.files = []
                }
                if (!modalForm.value.project_images) {
                  modalForm.value.project_images = []
                }
                api.getallgoodssku({ goods_id: modalForm.value.goods_id }).then((res) => {
                  data.skuOptions = res.data
                })
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          [[vPermission, 'post/api/content/contents/update']]
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ data_id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                [[vPermission, 'delete/api/content/contents/delete']]
              ),
            default: () => h('div', {}, '确定删除该数据吗?'),
          }
        ),
      ]
    },
  },
]

async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.status = row.status === false ? true : false
  row.publishing = false
  try {
    await api.updateSettingProject(row)
    $message?.success(row.status ? '正常' : '禁用')
    $table.value?.handleSearch()
  } catch (err) {
    // 有异常恢复原来的状态
    row.status = row.status === false
  } finally {
    row.publishing = false
  }
}




let lastClickedNodeId = null
const validateAddUser = {
  name: [
    {
      required: true,
      message: '请输入标题',
      trigger: ['input', 'blur'],
    },
  ],
  type: [
    {
      required: true,
      message: '请选择项目类别',
      trigger: ['input', 'blur','change'],
      type: 'number',
    },
  ]
}

const nodeProps = ({ option }) => {
  return {
    onClick() {
      if (lastClickedNodeId === option.id) {
        $table.value?.handleSearch()
        lastClickedNodeId = null
      } else {
        api.getContents({ parent_id: option.id }).then((res) => {
          $table.value.tableData = res.data
          lastClickedNodeId = option.id
        })
      }
    },
  }
}

function handleGoodsChange() {
      // 根据选择的商品ID更新商品规格选项
      api.getallgoodssku({ goods_id: modalForm.value.goods_id }).then((res) => {
          data.skuOptions = res.data
        })
      modalForm.value.sku_id = null  // 清空已选择的规格
    }
</script>

<template>
      <CommonPage show-footer title="项目列表">
        <template #action>
          <NButton
            v-permission="'post/api/content/contents/create'"
            type="primary"
            @click="handleAdd"
          >
            <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />新建项目
          </NButton>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getSettingProject"
          :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem label="名称" :label-width="40">
              <NInput
                v-model:value="queryItems.name"
                clearable
                type="text"
                placeholder="请输入名称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>
          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="80"
            :model="modalForm"
            :rules="validateAddUser"
          >

              <NFormItem label="项目名称" path="name" style="width: 100%">
                <NInput v-model:value="modalForm.name" clearable placeholder="请输入项目名称" />
              </NFormItem>
              <NFormItem label="排序" path="sort">
                <NInputNumber
                  style="width: 200px"
                  v-model:value="modalForm.sort"
                  clearable
                  placeholder="输入排序"
                  :default-value="0"
                />
              </NFormItem>

              <NFormItem label="父级分类" path="type">
          <NTreeSelect
            v-model:value="modalForm.type"
            :options="data.ProjectData"
            key-field="id"
            label-field="name"
            placeholder="请选择项目分类"
            clearable
            default-expand-all

          ></NTreeSelect>
        </NFormItem>
            <NFormItem label="封面图" path="avatar">
              <NImage v-if="modalForm.cover" width="60" style="border-radius: 5px;margin-right: 15px;" :src="modalForm.cover"></NImage>
              <NUpload :action="data.uploadAction" :headers="{ token: data.token }" :max="1" :show-file-list=false
                       :custom-request="customRequestMethod" list-type="image">
                <NButton >上传</NButton>
              </NUpload>
            </NFormItem>
              <NFormItem label="仪器编号" path="pid">
                <NSelect
                  style="width: 300px"
                  v-model:value="modalForm.pid"
                  :options="data.InstiumentData.value"
                  placeholder="请选择仪器编号"
                />
              </NFormItem>
              <NFormItem label="时长(分钟)" path="interval">
                <NInputNumber
                  style="width: 200px"
                  v-model:value="modalForm.interval"
                  clearable
                  placeholder="输入时长(分钟)"
                />
              </NFormItem>

            <NFormItem label="关联商品" path="goods_id">
            <NSelect
                  style="width: 500px"
                  v-model:value="modalForm.goods_id"
                  :options="data.goods"
                  placeholder="请选择商品"
                  clearable
                  filterable
                  @update:value="handleGoodsChange"
                />
              </NFormItem>

            <NFormItem label="商品规格" path="sku_id">
            <NSelect
                  style="width: 500px"
                  v-model:value="modalForm.sku_id"
                  :options="data.skuOptions"
                  placeholder="请选择商品规格"
                  filterable
                  clearable
                />
              </NFormItem>
            <NFormItem label="介绍组图" path="project_images" style="width: 100%">
              <NUpload
                  :action="data.uploadAction"
                  :headers="{ token: data.token }"
                  multiple
                  list-type="image-card"
                  @finish="handleFinish"
                  v-model:file-list="modalForm.project_images"
              >
              </NUpload>
            </NFormItem>

          </NForm>
        </CrudModal>
      </CommonPage>
  <!-- 业务页面 -->
</template>
